package com.cn.kehong.service;

import com.cn.kehong.api.IProductDianciPeriodService;
import com.cn.kehong.api.IProductGzPeriodService;
import com.cn.kehong.api.IProductSaojiePeriodService;
import com.cn.kehong.api.IXunjianTaskService;
import com.cn.kehong.dao.ProductSaojieJobMapper;
import com.cn.kehong.dao.ProductSaojiePeriodMapper;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.CollectionsUtil;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.cn.kehong.utils.QueryForm;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ProductSaojiePeriodServiceImpl implements IProductSaojiePeriodService {

    @Autowired
    private ProductSaojiePeriodMapper productSaojiePeriodMapper;

    @Autowired
    private ProductSaojieJobMapper productSaojieJobMapper;

    @Autowired
    private IProductGzPeriodService productGzPeriodService;

    @Autowired
    private IProductDianciPeriodService productDianciPeriodService;

    @Autowired
    private IXunjianTaskService xunjianTaskService;

    @Override
    public List<ProductSaojiePeriod> getProductSaojiePeriodList(QueryForm queryForm) throws Exception {
        int count = productSaojiePeriodMapper.selectProductSaojiePeriodCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<ProductSaojiePeriod> productSaojiePeriods = productSaojiePeriodMapper.selectProductSaojiePeriods(queryForm);
        productSaojiePeriods.get(0).setCount(count);
        return productSaojiePeriods;
    }

    @Override
    public List<ProductSaojiePeriod> getProductSaojiePeriodsByStatus() throws Exception {
        return productSaojiePeriodMapper.selectProductSaojiePeriodsByStatus();
    }

    @Override
    public List<ProductSaojieJob> getProductSaojieJobList(QueryForm queryForm) throws Exception {
        int count = productSaojieJobMapper.selectProductSaojieJobCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<ProductSaojieJob> productSaojieJobs = productSaojieJobMapper.selectProductSaojieJobs(queryForm);
        productSaojieJobs.get(0).setCount(count);
        return productSaojieJobs;
    }

    @Override
    public List<ProductSaojieJob> getProductSaojieJobsById(String saojieId) throws Exception {
        if(StringUtils.isEmpty(saojieId)){
            return Lists.newArrayList();
        }
        ProductSaojieJobExample example = new ProductSaojieJobExample();
        example.createCriteria().andSaojieIdEqualTo(saojieId);
        example.setOrderByClause("yao_guan_code asc");
        List<ProductSaojieJob> productSaojieJobs = productSaojieJobMapper.selectByExample(example);
        return productSaojieJobs;
    }

    @Override
    public List<ProductSaojiePeriod> getGzToSaojiePeriodDatas(String factoryName) throws Exception {
        return productSaojiePeriodMapper.selectGzToSaojiePeriodDatas(factoryName);
    }

    @Override
    public String addProductSaojiePeriod(String peiId,String productCode,String factoryName,String startCode) throws Exception {
        if(StringUtils.isEmpty(peiId)||StringUtils.isEmpty(productCode)||StringUtils.isEmpty(factoryName)){
            throw new Exception("peiId or productCode or factoryName is null");
        }
        ProductSaojiePeriodExample example = new ProductSaojiePeriodExample();
        example.createCriteria().andPeiIdEqualTo(peiId).andStatusEqualTo(Constants.NORMAL_STATUS);
        int existCount = productSaojiePeriodMapper.countByExample(example);
        if(existCount > 0){
            throw new Exception("ProductSaojiePeriod data has exist");
        }
        ProductSaojiePeriod productSaojiePeriod = new ProductSaojiePeriod();
        String id = CommonUtil.generateRandomNum("saojie-");
        productSaojiePeriod.setId(id);
        productSaojiePeriod.setFactoryName(factoryName);
        productSaojiePeriod.setProductCode(productCode);
        productSaojiePeriod.setStartCode(startCode);
        productSaojiePeriod.setPeiId(peiId);
        int count = productSaojiePeriodMapper.insertSelective(productSaojiePeriod);
        if(count < 1){
            throw new Exception("insert saojie data error");
        }
        return "";
    }

    @Override
    public String updateBatchProductSaojiePeriod(List<ProductSaojiePeriod> productSaojiePeriods) throws Exception {
        if(CollectionUtils.isEmpty(productSaojiePeriods)){
            return "数组为空";
        }
        List<ProductSaojieJob> productSaojieJobs = Lists.newArrayList();
        for(ProductSaojiePeriod productSaojiePeriod:productSaojiePeriods){
            if(CollectionUtils.isNotEmpty(productSaojiePeriod.getProductSaojieJobs())){
                productSaojieJobs.addAll(productSaojiePeriod.getProductSaojieJobs());
            }
        }
        int count = productSaojiePeriodMapper.batchUpdateSaojiePeriods(productSaojiePeriods);
        if(count < 1){
            return "更新表异常！";
        }
        if(CollectionUtils.isNotEmpty(productSaojieJobs)){
            count = productSaojieJobMapper.batchUpdateSaojieJobs(productSaojieJobs);
            if(count < 1){
                throw new Exception("更新表异常!!");
            }
        }
        return "";
    }

    @Override
    public String updateBatchProductSaojieJob(ProductSaojiePeriod productSaojiePeriod) throws Exception {
        List<ProductSaojieJob> productSaojieJobs = productSaojiePeriod.getProductSaojieJobs();
        if(CollectionsUtil.isEmpty(productSaojieJobs)){
            return "数组为空！";
        }
        String id = productSaojiePeriod.getId();
        if(StringUtils.isEmpty(id)){
            return "主键id为空";
        }
        ProductSaojiePeriod exist = productSaojiePeriodMapper.selectProductSaojiePeriodById(id);
        if(null == exist){
            return "烧结不存在！";
        }
        if(StringUtils.equals(exist.getSaojieStatus(),"2")){
            return "烧结已经结束";
        }

        List<String> guanCodes = productSaojieJobMapper.selectJobGuanCodeBySaojieId(id);
        if(CollectionsUtil.isEmpty(guanCodes)){
            return "烧结已经结束";
        }
        String saojieStatus = "1";
        if(guanCodes.size() == productSaojieJobs.size()){
            saojieStatus = "2";
        }
        String dianuciCode = "";
        String firstGuanCode = exist.getYaoGuanCode().split("/")[0];
        int code = Integer.parseInt(firstGuanCode);
        if(code <=2){
            dianuciCode = "01-02";
        }else if(code <=4){
            dianuciCode = "03-04";
        }else if(code <=6){
            dianuciCode = "05-06";
        }else if(code <=8){
            dianuciCode = "07-08";
        }else if(code <=10){
            dianuciCode = "09-10";
        }else if(code <=12){
            dianuciCode = "11-12";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String endTime = simpleDateFormat.format(new Date());
        ProductDianciPeriod productDianciPeriod = new ProductDianciPeriod();
        productDianciPeriod.setPeiId(exist.getPeiId());
        productDianciPeriod.setFactoryName(exist.getFactoryName());
        productDianciPeriod.setProductCode(exist.getProductCode());
        productDianciPeriod.setFullYaoGuan(exist.getYaoGuanCode());
        productDianciPeriod.setDianciGuanCode(dianuciCode);
        productDianciPeriod.setDianciStartTime(endTime);
        if(productSaojieJobs.size() == 1){
            productDianciPeriod.setYaoGuanCode(productSaojieJobs.get(0).getYaoGuanCode());
        }else{
            productDianciPeriod.setYaoGuanCode(exist.getYaoGuanCode());
        }
        productDianciPeriod.setDianciStatus("1");
        productDianciPeriod.setStartCode(exist.getStartCode());
        for(ProductSaojieJob job:productSaojieJobs){
            if(!guanCodes.contains(job.getYaoGuanCode())){
                return "参数异常！";
            }
            job.setSaojieJobStatus("1");
            job.setValue15(endTime);
            job.setDianChuciCode(dianuciCode);
        }
        int  count = productSaojieJobMapper.batchUpdateSaojieJobs(productSaojieJobs);
        if(count < 1){
            return "更新表异常！";
        }
        ProductSaojiePeriod update = new ProductSaojiePeriod();
        update.setHasOut("1");
        update.setSaojieStatus(saojieStatus);
        ProductSaojiePeriodExample example = new ProductSaojiePeriodExample();
        example.createCriteria().andIdEqualTo(id);
        count = productSaojiePeriodMapper.updateByExampleSelective(update,example);
        if(count <1){
            throw new Exception("更新表异常！！");
        }

        String resp = productDianciPeriodService.addProductDianciPeriod(productDianciPeriod);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateBatchProductSaojieJobByRedis(List<ProductSaojieJob> productSaojieJobs) throws Exception {
        if(CollectionsUtil.isEmpty(productSaojieJobs)){
            return "数组为空";
        }
        int count = productSaojieJobMapper.batchUpdateSaojieJobs(productSaojieJobs);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateGzPeriodEnterYaolu(ProductSaojiePeriod productSaojiePeriod) throws Exception {
        String yaolu = productSaojiePeriod.getYaoGuanCode();
        if(StringUtils.isEmpty(yaolu)){
            return "缺少窑炉";
        }
        String peiId = productSaojiePeriod.getPeiId();
        if(StringUtils.isEmpty(peiId)){
            return "缺少peiId";
        }
        ProductSaojiePeriodExample example = new ProductSaojiePeriodExample();
        example.createCriteria().andPeiIdEqualTo(peiId).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<ProductSaojiePeriod> productSaojiePeriods = productSaojiePeriodMapper.selectByExample(example);
        if(CollectionsUtil.isEmpty(productSaojiePeriods)||productSaojiePeriods.size()!=1){
            return "烧洁数据异常！";
        }
        ProductSaojiePeriod exist = productSaojiePeriods.get(0);
        ProductSaojieJobExample jobExample = new ProductSaojieJobExample();
        jobExample.createCriteria().andSaojieIdEqualTo(exist.getId()).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<ProductSaojieJob> jobs = productSaojieJobMapper.selectByExample(jobExample);

        if(jobs.size() >0){
            return "数据已经存在！";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = simpleDateFormat.format(new Date());
        productSaojiePeriod.setStartTime(startTime);
        productSaojiePeriod.setSaojieStatus("1");
        int count = productSaojiePeriodMapper.updateByExampleSelective(productSaojiePeriod,example);
        if(count < 0){
            return "更新烧洁异常！";
        }

        List<ProductSaojieJob> productSaojieJobs = Lists.newArrayList();
        String yaolus[] = yaolu.split("/");
        for(int i = 0 ;i < yaolus.length;i++){
            String yaol = yaolus[i];
            if(StringUtils.isEmpty(yaol)){
                continue;
            }
            ProductSaojieJob job = new ProductSaojieJob();
            job.setValue14(productSaojiePeriod.getJinliaoStartTime());
            //进料结束时间
            job.setValue20(productSaojiePeriod.getEndTime());
            job.setSaojieId(exist.getId());
            job.setYaoGuanCode(yaolus[i]);
            job.setYaoGuanStatus("1");
            job.setSaojieJobStatus("0");
//            job.setDianChuciCode(yaolu);
            job.setId(CommonUtil.generateRandomNum("sjob-"));
            productSaojieJobs.add(job);
        }
        count = productSaojieJobMapper.batchInsertProductSaojieJobs(productSaojieJobs);
        if(count < 1){
            throw new Exception("更新表异常!!");
        }

        String resp = productGzPeriodService.updateGzJinLiaoPeriod(peiId);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }

        resp = xunjianTaskService.addXunjianYaoLuTask(exist.getStartCode(),exist.getFactoryName());
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return resp;
    }

    @Override
    public List<ProductSaojieJob> getProductSaojieJobBackList(QueryForm queryForm) throws Exception {
        int count = productSaojieJobMapper.getProductSaojieJobBackCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<ProductSaojieJob> productSaojieJobs = productSaojieJobMapper.getProductSaojieJobBackList(queryForm);
        productSaojieJobs.get(0).setCount(count);
        return productSaojieJobs;
    }
}
